#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 2025 Huawei Technologies Co., Ltd. All rights reserved.

from ansible.module_utils.basic import AnsibleModule

from openubmc_ansible.openubmc_logger import report
from openubmc_ansible.openubmc_logger import log
from openubmc_ansible.openubmc_redfish_api.api_outband_fw_update import update_fw
from openubmc_ansible.openubmc_redfish_api.redfish_base import BmcBaseConnect
from openubmc_ansible.utils import ansible_bmc_run_module
from openubmc_ansible.utils import is_support_server
from openubmc_ansible.utils import SERVERTYPE
from openubmc_ansible.utils import set_result
from openubmc_ansible.utils import remote_file_path


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = """
module: openubmc_outband_fw_update
short_description: update outband firmware
version_added: "2.5.0"
description: update outband firmware
options:
  openubmc_ip:
    required: true
    default: None
    description:
      - openUBMC IP address
  openubmc_user:
    required: true
    default: None
    description:
      - openUBMC user name used for authentication
  openubmc_pswd:
    required: true
    default: None
    description:
      - openUBMC user password used for authentication
  local_file:
    required: false
    default: None
    description:
      - local firmware path
  remote_file:
    required: false
    default: None
    description:
      - remote firmware path or openubmc file path
  file_server_user:
    required: false
    default: None
    description:
      - remote file server user name
  file_server_pswd:
    required: false
    default: None
    description:
      - remote file server password
"""

EXAMPLES = r"""
  - name: update outband fw
    openubmc_outband_fw_update:
      openubmc_ip: "{{ openubmc_ip }}"
      openubmc_user: "{{ openubmc_user }}"
      openubmc_pswd: "{{ openubmc_pswd }}"
      local_file: "/home/plugin/cpldimage.hpm"
"""

RETURNS = """

"""


def openubmc_outband_fw_update_module(module):
    """
    Function: Outband firmware upgrade
    Args:
        module : information from yml
    Returns:
        ret : Task result
            "result": True or False
            "msg": description for success or failure
    Raises:
        None
    Date: 2019/10/9 20:30
    """
    with BmcBaseConnect(module.params, log, report) as openubmc:
        ret = is_support_server(openubmc, SERVERTYPE)
        if ret['result']:
            all_file = (module.params.get("local_file"), module.params.get("remote_file"))
            if all(all_file) or not any(all_file):
                log_error = "Please select an out-of-band firmware upgrade " \
                            "mode from local_file and remote_file."
                set_result(openubmc.log_error, log_error, False, ret)
                return ret
        try:
            local, file, protocol = get_file_name(module)
        except Exception as e:
            log_error = "Update failed! %s" % str(e)
            set_result(openubmc.log_error, log_error, False, ret)
            return ret

        ret = update_fw(openubmc, file, protocol, local)
    return ret


def get_file_name(module):
    """
    Function: Obtain the name of the upgrade package.
    Args:
        module: information from yml
    Returns:
        local: Whether to upload the upgrade package from the local host
        file: the name of the upgrade package
        protocol: File Server Protocol
    """
    protocol = None
    local = False
    file = module.params.get("local_file") or module.params.get("remote_file")
    if file == module.params.get("local_file"):
        local = True
    elif not file.startswith("/tmp"):
        file = remote_file_path(file, module)
        protocol, server_path = file.split("://")
        protocol = protocol.upper()
    return local, file, protocol


def main():
    module = AnsibleModule(
        argument_spec={
            "openubmc_ip": {"required": True, "type": 'str'},
            "openubmc_user": {"required": True, "type": 'str'},
            "openubmc_pswd": {"required": True, "type": 'str', "no_log": True},
            "local_file": {"required": False, "type": 'str'},
            "remote_file": {"required": False, "type": 'str'},
            "file_server_user": {"required": False, "type": 'str', "no_log": True},
            "file_server_pswd": {"required": False, "type": 'str', "no_log": True}
        },
        supports_check_mode=False)
    ansible_bmc_run_module(openubmc_outband_fw_update_module, module, log, report)


if __name__ == '__main__':
    main()
